#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from flask import Flask, jsonify
from flask.cli import load_dotenv
from flask_cors import CORS

from .extensions import db, migrate
from .api import register_blueprints
from .config import config_by_name


def create_app(config_name="default"):
    """应用工厂函数，创建并配置Flask应用实例
    
    Args:
        config_name: 配置名称，默认为default
        
    Returns:
        Flask应用实例
    """
    # 加载环境变量
    load_dotenv()
    
    app = Flask(__name__, instance_relative_config=True)
    
    # 加载配置
    app.config.from_object(config_by_name[config_name])
    app.config.from_pyfile('config.py', silent=True)
    
    # 确保实例文件夹存在
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass
    
    # 配置CORS，允许前端跨域访问
    CORS(app, resources={r"/api/*": {"origins": "*"}})
    
    # 注册扩展
    register_extensions(app)
    
    # 注册蓝图
    register_blueprints(app)
    
    # 注册错误处理器
    register_error_handlers(app)
    
    return app


def register_extensions(app):
    """注册Flask扩展"""
    db.init_app(app)
    migrate.init_app(app, db)


def register_error_handlers(app):
    """注册全局错误处理器"""
    @app.errorhandler(400)
    def bad_request(e):
        return jsonify({"error": "Bad Request", "message": str(e)}), 400
    
    @app.errorhandler(404)
    def not_found(e):
        return jsonify({"error": "Not Found", "message": str(e)}), 404
    
    @app.errorhandler(500)
    def internal_server_error(e):
        return jsonify({"error": "Internal Server Error", "message": str(e)}), 500

    @app.errorhandler(422)
    def unprocessable_entity(e):
        return jsonify({"error": "Validation Error", "message": str(e)}), 422
